package com.onepower.admin.authorization;

import com.onepower.core.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author lixiaofeng
 * @date 2019/12/31 15:47
 */
@Slf4j
@Component
public class URLInterceptor implements HandlerInterceptor {


    private TokenHelper tokenHelper;

    public URLInterceptor( TokenHelper tokenHelper) {
        log.info("URLInterceptor --- 拦截器构造");
        this.tokenHelper = tokenHelper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle 开始执行!");
        System.out.println(request.getRequestURI());
        try {
            String token = tokenHelper.getToken(request);
            if (token != null){
                Map<String,Object> userMap = tokenHelper.getDecryptString(token);
                if (userMap != null){
                    HttpSession session = request.getSession();
                    session.setAttribute("user",userMap);
                 return true;
                }
                return false;
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        log.info("preHandle 执行完成!");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle run!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion run!");
    }
}
